package app;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.sql.SQLException;

import BD.BDDML;
import GUI.MainWindow;

public class ListenerMulticast implements Runnable {
	
	private static BDDML banco=null;
	private MainWindow mw = null;
		
	public ListenerMulticast(MainWindow m) {
		if (mw == null)
			mw = m;
	}

	static public void main(String[] args) {
		
	}

	public void run() {
		InetAddress grupo = null;
		MulticastSocket s = null;
		try {
			banco = new BDDML("Estoque");
			grupo = InetAddress.getByName("224.0.0.1");
			s = new MulticastSocket(2000);
			System.out.println("Listener join the group.");
			s.joinGroup(grupo);
			System.out.println("+ All set.");

			while ( true ) {
				byte[] buf = new byte[1000];
				DatagramPacket DGReceive = new DatagramPacket(buf, buf.length);
				System.out.print("==> * Aguardando mensagem ");
				s.receive(DGReceive);
				byte[] dest = new byte[DGReceive.getLength()];
				System.arraycopy(DGReceive.getData(), 0, dest, 0, dest.length);
				String arrived = new String(dest);
				System.out.println("Chegou # "+arrived+" #");
				banco.Executa(arrived);
				try{Thread.sleep(800L);} catch (InterruptedException e) {}
				mw.refreshTable(null);
			}
		} catch (UnknownHostException e) {
			System.err.println("Excessao causada pelo InetAddress.");
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("Excessao causada pelo Multicast.");
			e.printStackTrace();
		} catch (Exception e) {
			System.err.println("Excessao geral desconhecida.");
			e.printStackTrace();
		} finally {
			System.out.println("Saindo do grupo ...");
			try {
				s.leaveGroup(grupo);
				banco.Close();
			} catch (IOException e) {
				System.err.println("Imagine erro ao fechar o grupo.");
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			System.out.println("Ok.");
		}
		
	}
}
